﻿using System;
using System.Collections.Generic;
using System.Data;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Gift.DAL;
using Gift.Model;

namespace WebSite.cn
{
    public partial class ProfessionArea :BasePage
    {
        readonly DALCard theCard = new DALCard();
        readonly OrderAccount theOrderAccount = new OrderAccount();
        readonly DALShoppro theShoppro = new DALShoppro();

        public string sLoginMessage = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            Session["backHref"] = Request.Url.PathAndQuery;
          
            if (!IsPostBack)
            {
                if (!string.IsNullOrEmpty(Request.QueryString["msg"]) && LoginMember.UserCardCodeList == null)
                {
                    sLoginMessage = "<font color='red' size='3'>提示：请输入礼品卡卡号和密码，到专区选取您要兑换的商品！</font>";
                }
          
                if ( LoginMember.UserCardCodeList != null)
                {
                    this.lbtnExit.Visible = true ;
                }
                else
                {
                    this.lbtnExit.Visible = false;
                }
                if (!string.IsNullOrEmpty(Request.QueryString["pid"]) && string.IsNullOrEmpty(Request.QueryString["isView"]))
                {
                    this.category_1.Visible = false;
                    this.productsList.Visible = false;
                    return;
                }

                BuildProductList();
            }
        }

        protected void txtSubmit_Click(object sender, EventArgs e)
        {
            if(string.Compare(this.txtValidate.Text.Trim(), Session["checkCode"].ToString()) != 0)
            {
                base.Response.Write("<script language='javascript'>alert('验证码不正确！请重新输入！');window.location.href='ProfessionArea.aspx';</script>");
                base.Response.End();
            }

            dbCard oCard;
            oCard = theCard.GetModel(this.txtCardCode.Text.Trim(), this.txtPassword.Text.Trim(),null);
            if (oCard != null)
            {
              
                if (oCard.states == 0)
                {
                      base.Response.Write("<script language='javascript'>alert('该卡还未激活，请先开卡后才能使用！');window.location.href='ProfessionArea.aspx';</script>");
                        base.Response.End();
                }
                else if (oCard.states == 2)
                {
                    base.Response.Write("<script language='javascript'>alert('该卡已被使用！');window.location.href='ProfessionArea.aspx';</script>");
                    base.Response.End();
                }
                else if (oCard.states == 3)
                {
                    base.Response.Write("<script language='javascript'>alert('该卡已失效！');window.location.href='ProfessionArea.aspx';</script>");
                    base.Response.End();

                }
                else if (oCard.states == 4)
                {
                    base.Response.Write("<script language='javascript'>alert('该卡还未激活,请先开卡后才能使用！');window.location.href='ProfessionArea.aspx';</script>");
                    base.Response.End();
                }
                else if (oCard.endtime < DateTime.Now.Date)
                {
                    if (oCard.lasttime >= DateTime.Now.Date)
                    {
                        base.Response.Write("<script language='javascript'>alert('该卡的专区有效时间已过,只能到礼品商城兑换商品！');window.location.href='ProfessionArea.aspx';</script>");
                        base.Response.End();
                    }
                    else
                    {
                        base.Response.Write("<script language='javascript'>alert('该卡已失效！');window.location.href='ProfessionArea.aspx';</script>");
                        base.Response.End();
                    }
                }
                else if (oCard.states == 1)
                {
                    this.productsList.CurrentPageIndex = 0;
                    if (LoginMember.UserCardCodeList != null)
                    {

                        UserCard oCard1 = new UserCard();
                        DALCard oCardCampa = new DALCard();
                        if (LoginMember.UserCardCodeList[0].UserCardTypeId == oCard.cardtypeId.ToString())
                        {
                            bool bHasCard = false;
                            foreach (UserCard tempCard in LoginMember.UserCardCodeList)
                            {
                                if (tempCard.UserCardCode == txtCardCode.Text.Trim())
                                {
                                    bHasCard = true;
                                }
                            }
                            if (!bHasCard)
                            {
                                oCard1.UserCardId = oCard.cardid.ToString();
                                oCard1.UserCardCode = txtCardCode.Text.Trim();
                                oCard1.UserCardPassword = txtPassword.Text.Trim();
                                oCard1.UserCardPrice = oCard.cardprice.ToString();
                                oCard1.UserCardTypeId = oCard.cardtypeId.ToString();
                                LoginMember.UserCardCodeList.Add(oCard1);
                            }
                        }
                        else
                        {
                            base.Response.Write("<script language='javascript'>alert('只能添加同类卡！');window.location.href='ProfessionArea.aspx';</script>");
                            base.Response.End();
                        }
                    }
                    else
                    {
                        LoginMember.UserCardCodeList = new List<UserCard>();
                        UserCard oCard2 = new UserCard();
                        oCard2.UserCardId = oCard.cardid.ToString();
                        oCard2.UserCardCode = txtCardCode.Text.Trim();
                        oCard2.UserCardPassword = txtPassword.Text.Trim();
                        oCard2.UserCardPrice = oCard.cardprice.ToString();
                        oCard2.UserCardTypeId = oCard.cardtypeId.ToString();
                        LoginMember.UserCardCodeList.Add(oCard2);
                    }

                    this.divLogin.Visible = false;
                    this.lbtnExit.Visible = true;


                    if (!string.IsNullOrEmpty(base.Request.QueryString["pid"]))
                    {
                        DataTable dtProduct = new DataTable();
                        dtProduct = SQLAccess.GreatDs(" select CT.id from tbCardType CT join DB_Shoppro S on CT.ProfessionAreaTypeId = S.ProfessionAreaTypeId where S.proid=" + base.Request.QueryString["pid"]).Tables[0];

                        if (oCard.cardtypeId != int.Parse(dtProduct.Rows[0]["id"].ToString()))
                        {
                            Response.Redirect("ProfessionArea.aspx?page=1");
                            return;
                        }
                    }

                    if(!string.IsNullOrEmpty(Request.QueryString["pid"]))
                    {
                        DataTable table;
                        string str2;
                       if ((re.ReadCookie("tempno") == null) || (re.ReadCookie("tempno") == ""))
                            {
                                try
                                {
                                    SQLAccess.DoSql("update DB_Temp set tempid=tempid+1");
                                    string sql = "select tempid from DB_Temp";
                                    table = SQLAccess.GreatDs(sql).Tables[0];
                                    re.WriteCookie("tempno", table.Rows[0][0].ToString(), 360);
                                }
                                catch { }
                            }
                            string strPrice = "0";
                            string strContent = "";
                            string strProdNum = "0";
                            string strPid = "";
                            strPid = base.Request.QueryString["pid"];
                            strPrice = base.Request.QueryString["price"].ToString();
                            strContent = base.Request.QueryString["content"].ToString();
                            strProdNum = base.Request.QueryString["pronum"].ToString();

                           string tempId = string.Empty;
                            if (LoginMember.UserCardCodeList != null)
                            {
                                tempId = LoginMember.UserCardCodeList[0].UserCardCode;
                            }
                            else if (LoginMember != null)
                            {
                                tempId = LoginMember.MemberId.ToString();
                            }
                            else
                            {
                                tempId = re.ReadCookie("tempno");
                            }
                            if(string.IsNullOrEmpty(tempId))
                            {
                                tempId = "0";
                            }

                            table = SQLAccess.GreatDs("select top 1 carid,pronum,price,score from DB_Car where productid=" + strPid + " and temp=" + tempId + " and contents='" + strContent + "' and flag=0").Tables[0];
                            if (table.Rows.Count > 0)
                            {
                                str2 = "update DB_Car set pronum=" + strProdNum + ",sumprice=" + Convert.ToString((float) (Convert.ToSingle(strProdNum) * Convert.ToSingle(table.Rows[0]["price"]))) + ",sumscore=" + Convert.ToString((float) (Convert.ToSingle(strProdNum) * Convert.ToSingle(table.Rows[0]["score"]))) + " where carid=" + table.Rows[0]["carid"].ToString() + "";
                            }
                            else
                            {
                                str2 = "insert into DB_Car (productid,memberid,pronum,state,flag,price,contents,temp,sumprice,score,sumscore) values (" + strPid + ",0," + strProdNum + ",0,0," + strPrice + ",'" + strContent + "'," + tempId + "," + Convert.ToString((float)(Convert.ToSingle(strProdNum) * Convert.ToSingle(strPrice))) + ",0,0)";
                            }
                            SQLAccess.DoSql(str2);
                            base.Response.Write("<script language='javascript'>window.location.href='account.aspx?type=1';</script>");
                            base.Response.End();

                    }
                    Response.Redirect("ProfessionArea.aspx?page=1&sid=" + Request.QueryString["sid"]);
                   
                }
                else
                {
                    base.Response.Write("<script language='javascript'>alert('该卡已被使用！');window.location.href='ProfessionArea.aspx?sid=" + Request.QueryString["sid"] + "';</script>");
                    base.Response.End();
                }
            }
            else
            {
                base.Response.Write("<script language='javascript'>alert('卡号或密码不正确！');window.location.href='ProfessionArea.aspx?sid=" + Request.QueryString["sid"] + "';</script>");
                base.Response.End();
            }
        }

        void BuildProductList(int iCardTypeId)
        {

            DataSet ds;
            ds = theShoppro.GetListByCardTypeId(iCardTypeId);
            if (ds.Tables.Count > 0)
            {
                this.productsList.DataSource = ds.Tables[0].DefaultView;
                this.productsList.DataBind();
            }
        }

        void BuildProductList()
        {
            DataSet ds;
            string sOrderBy = string.Empty;
            if (string.IsNullOrEmpty(Request.QueryString["order"]) || Request.QueryString["order"] == "sale")
            {
                sOrderBy = " order by saleCount {0} ";
                if (this.productsList.ArrowDirectionSale == "&darr;")
                {
                    sOrderBy = string.Format(sOrderBy, "ASC");
                }
                else
                {
                    sOrderBy = string.Format(sOrderBy, "DESC");
                }
            }
            else if (Request.QueryString["order"] == "price")
            {
                sOrderBy = " order by proprice1 {0} ";
                if (this.productsList.ArrowDirectionPrice == "&darr;")
                {
                    sOrderBy = string.Format(sOrderBy, "ASC");
                }
                else
                {
                    sOrderBy = string.Format(sOrderBy, "DESC");
                }
            } else if (Request.QueryString["order"] == "time")
            {
                 sOrderBy = " order by saleTime desc ";
            }

            ds = theShoppro.GetListForProfession(Request.QueryString["typeid"], sOrderBy);
            if (ds.Tables.Count > 0)
            {
                this.productsList.DataSource = ds.Tables[0].DefaultView;
                this.productsList.DataBind();
            }
        }


        protected void PageChanged(object sender, DataGridPageChangedEventArgs e)
        {
            dbCard oCard;
            this.productsList.CurrentPageIndex = e.NewPageIndex;
            
            if (LoginMember.UserCardCodeList != null)
            {
                decimal dTotalCardPrice = 0;
                for (int i = 0; i < LoginMember.UserCardCodeList.Count; i++)
                {
                    dTotalCardPrice += decimal.Parse(LoginMember.UserCardCodeList[i].UserCardPrice);
                }
                this.lblMoneyMessage.Text = "您的礼品卡余额为:" + dTotalCardPrice.ToString() + ",请选取您要购买的商品！";
                oCard = theCard.GetModel(LoginMember.UserCardCodeList[0].UserCardCode, LoginMember.UserCardCodeList[0].UserCardPassword,null);
              
                this.BuildProductList(oCard.cardtypeId);
            }
            else
            {
                this.BuildProductList();
            }

        }


        protected void productsList_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
            {
                Label label = (Label)e.Item.FindControl("price");
                Label label2 = (Label)e.Item.FindControl("Label1");
                Image image = (Image)e.Item.FindControl("Image2");
                if ((label.Text == "0") || (label.Text == "0.00"))
                {
                    label.Text = label2.Text;
                }
                if (image.ImageUrl.ToString() == "")
                {
                    image.ImageUrl = "../uploadfile/banner/" + info.info1("", "shopmopic");
                }

            }
        }

        protected void lbtnExit_Click(object sender, EventArgs e)
        {
            base.LoginMember.UserCardCodeList = null;
          
            Response.Redirect("index.aspx");
        }

    }
}